package com.bsoft.advance.client.config;

import com.bsoft.advance.client.processor.RpcClientProcessor;
import com.bsoft.advance.core.balancer.RoundRobinBalance;
import com.bsoft.advance.core.balancer.LoadBalance;
import com.bsoft.advance.core.common.RpcClientProperties;
import com.bsoft.advance.core.register.DiscoveryService;
import com.bsoft.advance.core.register.zk.ZookeeperDiscoveryService;
import org.springframework.boot.context.properties.bind.Binder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.env.Environment;

@Configuration
public class BeanConfiguration {

    /**
     * 绑定环境变量到metadata上
     * @param environment
     * @return
     */
    @Bean
    public RpcClientProperties requestMetadata(Environment environment){
        RpcClientProperties properties = Binder.get(environment).bind("rpc.client", RpcClientProperties.class).get();
        return properties;
    }

    /**
     * 后置处理类
     */
    @Bean
    public RpcClientProcessor rpcClientProcessor(RpcClientProperties properties,DiscoveryService discoveryService){
        return new RpcClientProcessor(properties, discoveryService);
    }

    /**
     * 负载均衡策略
     */
    @Bean
    public LoadBalance loadBalance() {
        return new RoundRobinBalance();
    }

    /**
     * 服务发现
     */
    @Bean
    public DiscoveryService discoveryService(RpcClientProperties properties,LoadBalance balance) {
        return new ZookeeperDiscoveryService(properties.getDiscoveryAddr(), balance);
    }
}
